using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Nirvana
{
    public class RuntimeMeshBlocks : SquareBlock<RuntimeMeshBlock>
    {
        private HashSet<RuntimeMeshBlock> _lastBlock = new HashSet<RuntimeMeshBlock>();
        private HashSet<RuntimeMeshBlock> _nowBlock = new HashSet<RuntimeMeshBlock>();

        /// <summary>
        /// 更新需要显示的块，加载新的需要显示的块，卸载不需要显示的块
        /// </summary>
        /// <param name="playerPos">玩家位置</param>
        /// <param name="offsetDistance">相机移动差值</param>
        public override void Update(ref Vector3 playerPos, float offsetDistance)
        {
            if (!IsNeedUpdate(offsetDistance))
            {
                return;
            }

            CalcBoundary(ref playerPos, out int minX, out int minZ, out int maxX, out int maxZ);
            _nowBlock.Clear();
            for (int i = minX; i < maxX; i++)
            {
                for (int j = minZ; j < maxZ; j++)
                {
                    RuntimeMeshBlock block = FindBlock(i, j);
                    if (block != null)
                    {
                        block.Load();
                        _nowBlock.Add(block);
                        if (_lastBlock.Contains(block))
                        {
                            _lastBlock.Remove(block);
                        }
                    }
                }
            }

            foreach (var block in _lastBlock)
            {
                block.UnLoad();
            }

            _lastBlock.Clear();
            foreach (var block in _nowBlock)
            {
                _lastBlock.Add(block);
            }

            _nowBlock.Clear();
        }

        public override void UnInit()
        {
            _lastBlock.Clear();
            _nowBlock.Clear();
            base.UnInit();
        }
    }
}